<template>
  <pro-page-header content="字典数据" backRouteName="DictList">
    <div class="wrap">
      <pro-table
        ref="proTableInst"
        :tableTitle="'【' + type + '】' + '字典数据列表'"
        :columns="columns"
        :request="fetchDictDataPage"
        auto-height
        :relativeHeight="-47"
      >
        <template #operation>
          <n-space>
            <n-button
              v-hasPermi="`dictionaryData:add`"
              type="primary"
              @click="handleAddDict"
            >
              新增
            </n-button>
          </n-space>
        </template>
      </pro-table>

      <n-drawer
        v-model:show="drawerShow"
        :width="500"
        resizable
        :maskClosable="false"
        @after-leave="resetDictDataForm"
      >
        <n-drawer-content closable :title="handleTag">
          <pro-form
            ref="dictDataFormInst"
            v-model:form="dictDataForm"
            :options="dictDataFormOptions"
            :formProps="{
              labelPlacement: 'left'
            }"
          ></pro-form>

          <template #footer>
            <n-space>
              <n-button @click="drawerShow = false">取消</n-button>
              <n-button type="primary" @click="dictDataFormConfirm">
                确认
              </n-button>
            </n-space>
          </template>
        </n-drawer-content>
      </n-drawer>
    </div>
  </pro-page-header>
</template>

<script lang="ts" setup name="DictDataList">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import {
    useDictDataApi,
    useDictDataProForm,
    useDictDataProTable
  } from './hooks'

  const { id, type } = await getRouteQuery<{
    id: number
    type: string
  }>(['id', 'type'], {
    isEncrypt: true,
    isValid: true
  })

  const proTableInst = ref<ProTableInst | null>(null)
  const dictDataFormInst = ref<ProFormInst | null>(null)

  const drawerShow = ref(false)
  const handleType = ref<'add' | 'edit' | ''>('')
  const handleTag = computed(() =>
    handleType.value === 'add' ? '新增字典数据' : '修改字典数据'
  )
  const { dictDataForm, resetDictDataForm, dictDataFormOptions } =
    useDictDataProForm({ handleType })

  const handleAddDict = () => {
    handleType.value = 'add'
    drawerShow.value = true
  }

  const handleEditDict = (row) => {
    dictDataForm.value = row
    handleType.value = 'edit'
    drawerShow.value = true
  }

  const dictDataFormConfirm = async () => {
    if (await dictDataFormInst.value?.handleSubmit()) {
      fetchAddOrEditDictData()
    }
  }

  const { fetchDictDataPage, fetchAddOrEditDictData, fetchDelDictData } =
    useDictDataApi({
      id,
      type,
      handleType,
      handleTag,
      drawerShow,
      dictDataForm,
      proTableInst
    })
  const { columns } = useDictDataProTable({ handleEditDict, fetchDelDictData })
</script>

<style lang="less" scoped></style>
